package utils

import (
	"errors"
	"math/rand"
	"time"

	"github.com/dgrijalva/jwt-go"
)

/*
 +----------------------------------------------------------------------
 + Title        : token
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2018-01-06
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : jwt-go
 +----------------------------------------------------------------------
*/

type CustomClaims struct {
	Id string `json:"id"`
	jwt.StandardClaims
}

var secret = "golang963924556"

var TokenExpireTime = time.Hour * 24 * 3

// var TokenExpireTime = time.Minute

/**
 * 生成token
 *
 * @param string id -------------------------------------------必传
 * @return string, error
 */
func GenerateToken(id string) (string, error) {
	if id == "" {
		return "", errors.New("ID不能为空")
	}

	i := CustomClaims{
		id,
		jwt.StandardClaims{
			ExpiresAt: time.Now().Add(TokenExpireTime).Unix(),
			Issuer:    "trident", //签发人
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, i)
	return token.SignedString([]byte(secret))
}

/**
 * 解析token
 *
 * @param string token ----------------------------------------必传
 * @return *CustomClaims, error
 */
func ParseToken(token string) (*CustomClaims, error) {
	if token == "" {
		return nil, errors.New("token不能为空")
	}

	parseToken, err := jwt.ParseWithClaims(token, &CustomClaims{}, func(t *jwt.Token) (interface{}, error) {
		return []byte(secret), nil
	})

	if err != nil {
		return nil, err
	}

	if customClaims, ok := parseToken.Claims.(*CustomClaims); ok && parseToken.Valid {
		return customClaims, nil
	}

	return nil, err
}

/**
 * 清空token
 *
 * @param string id -------------------------------------------必传
 * @return error
 */
func ClearToken(id string) error {
	return nil
}

/**
 * 生成随机数
 *
 * @param int min ---------------------------------------------必传，100000
 * @param int max ---------------------------------------------必传，400000
 * @return int
 */
func CreateRandNum(min, max int) int {
	// 利用当前时间的UNIX时间戳初始化rand包
	rand.Seed(time.Now().UnixNano())
	return rand.Intn(max) + min
}
